package com.ruoyi.interview.service.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.interview.domain.*;
import com.ruoyi.interview.domain.entity.InterviewQuestionAnswerEntity;
import com.ruoyi.interview.domain.entity.ReportDetailEntity;
import com.ruoyi.interview.domain.entity.ReportDimensionDetail;
import com.ruoyi.interview.domain.entity.ReportResponseEntity;
import com.ruoyi.interview.mapper.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.interview.service.IInterviewReportService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 面试报告Service业务层处理
 * 
 * @author z5
 * @date 2025-06-19
 */
@Service
public class InterviewReportServiceImpl implements IInterviewReportService 
{
    @Autowired
    private InterviewReportMapper interviewReportMapper;
    @Autowired
    private InterviewDimensionMapper interviewDimensionMapper;
    @Autowired
    private InterviewQuestionMapper interviewQuestionMapper;
    @Autowired
    private InterviewDimensionScoreMapper interviewDimensionScoreMapper;
    @Autowired
    private InterviewRecordMapper interviewRecordMapper;
    @Autowired
    private InterviewPositionMapper interviewPositionMapper;
    /**
     * 查询面试报告
     * 
     * @param id 面试报告主键
     * @return 面试报告
     */
    @Override
    public InterviewReport selectInterviewReportById(Long id)
    {
        return interviewReportMapper.selectInterviewReportById(id);
    }

    /**
     * 查询面试报告列表
     * 
     * @param interviewReport 面试报告
     * @return 面试报告
     */
    @Override
    public List<InterviewReport> selectInterviewReportList(InterviewReport interviewReport)
    {
        return interviewReportMapper.selectInterviewReportList(interviewReport);
    }

    /**
     * 新增面试报告
     * 
     * @param interviewReport 面试报告
     * @return 结果
     */
    @Override
    public int insertInterviewReport(InterviewReport interviewReport)
    {
        interviewReport.setCreateTime(DateUtils.getNowDate());
        return interviewReportMapper.insertInterviewReport(interviewReport);
    }

    /**
     * 修改面试报告
     * 
     * @param interviewReport 面试报告
     * @return 结果
     */
    @Override
    public int updateInterviewReport(InterviewReport interviewReport)
    {
        interviewReport.setUpdateTime(DateUtils.getNowDate());
        return interviewReportMapper.updateInterviewReport(interviewReport);
    }

    /**
     * 批量删除面试报告
     * 
     * @param ids 需要删除的面试报告主键
     * @return 结果
     */
    @Override
    public int deleteInterviewReportByIds(Long[] ids)
    {
        return interviewReportMapper.deleteInterviewReportByIds(ids);
    }

    /**
     * 删除面试报告信息
     * 
     * @param id 面试报告主键
     * @return 结果
     */
    @Override
    public int deleteInterviewReportById(Long id)
    {
        return interviewReportMapper.deleteInterviewReportById(id);
    }

    /**
     * 生成面试记录对应的面试评价的提示词
     * @param recordId
     * @return
     */
    @Override
    public String genPrompt(Long recordId) {
        // 1、查询面试记录对应的岗位的维度
        List<InterviewDimension> interviewDimensions = interviewDimensionMapper.selectByRecordId(recordId);
        // 2、查询面试记录生成问题和回答的答案
        List<InterviewQuestionAnswerEntity> questionAnswers = interviewQuestionMapper.selectQuestionAnswerByRecordId(recordId);
        // 3、组织提示词字符串
        return genPromptString(interviewDimensions, questionAnswers);
    }

    /**
     * 将deepseek生成的评价保存至数据库
     * @param reportResponseEntity
     */
    @Override
    @Transactional
    public void saveReport(ReportResponseEntity reportResponseEntity) {
        // 面试报告表
        InterviewReport interviewReport = new InterviewReport();
        interviewReport.setCreateTime(DateUtils.getNowDate());
        interviewReport.setRecordId(reportResponseEntity.getRecordId());
        interviewReport.setOverallScore(reportResponseEntity.getOverall_score());
        interviewReport.setWeaknesses(reportResponseEntity.getWeaknesses());
        interviewReport.setSuggestions(reportResponseEntity.getSuggestions());
        interviewReport.setStrengths(reportResponseEntity.getStrengths());
        interviewReport.setGenerateTime(DateUtils.getNowDate());
        interviewReport.setOverallEvaluation(reportResponseEntity.getOverall_evaluation());
        interviewReportMapper.insertInterviewReport(interviewReport);
        // 维度得分表
        reportResponseEntity.getDimension_scores().forEach(interviewDimension -> {
            InterviewDimensionScore interviewDimensionScore = new InterviewDimensionScore();
            interviewDimensionScore.setReportId(interviewReport.getId());
            interviewDimensionScore.setScore(interviewDimension.getScore());
            interviewDimensionScore.setDimensionId(interviewDimension.getDimension_id());
            interviewDimensionScore.setEvaluation(interviewDimension.getEvaluation());
            interviewDimensionScore.setCreateTime(DateUtils.getNowDate());
            interviewDimensionScoreMapper.insertInterviewDimensionScore(interviewDimensionScore);
        });
    }

    @Override
    public int getResult(Long recordId) {
        return interviewQuestionMapper.selectAnswerResult(recordId);
    }

    /**
     * 列表当前登录人的面试报告
     * @return
     */
    @Override
    public List<InterviewReport> selectList() {
        // 当前登录人
        Long userId = SecurityUtils.getLoginUser().getUserId();
        return interviewReportMapper.selectListByUserId(userId);
    }

    /**
     * 查询报告详情
     * @param reportId
     * @return
     */
    @Override
    public ReportDetailEntity reportDetail(Long reportId) {
        // 查询报告
        InterviewReport interviewReport = interviewReportMapper.selectInterviewReportById(reportId);
        // 查询岗位
        Long recordId = interviewReport.getRecordId();
        InterviewRecord record = interviewRecordMapper.selectInterviewRecordById(recordId);
        Long positionId = record.getPositionId();
        InterviewPosition interviewPosition = interviewPositionMapper.selectInterviewPositionById(positionId);
        System.out.println("当前岗位ID positionId = " + positionId);
        // 查询岗位维度
        List<InterviewDimension> interviewDimensions = interviewDimensionMapper.selectByPositionId(positionId);
        System.out.print("查到的岗位维度id列表: ");
        for (InterviewDimension d : interviewDimensions) {
            System.out.print(d.getId() + " ");
        }
        System.out.println();
        // 查询维度得分
        InterviewDimensionScore interviewDimensionScore = new InterviewDimensionScore();
        interviewDimensionScore.setReportId(interviewReport.getId());
        List<InterviewDimensionScore> interviewDimensionScores = interviewDimensionScoreMapper.selectInterviewDimensionScoreList(interviewDimensionScore);
        // 组装ReportDetailEntity对象
        ReportDetailEntity reportDetailEntity = new ReportDetailEntity();
        BeanUtils.copyProperties(interviewReport,reportDetailEntity);
        reportDetailEntity.setPositionName(interviewPosition.getName());

//        List<ReportDimensionDetail> detailList = interviewDimensionScores.stream().map(score -> {
//            ReportDimensionDetail detail = new ReportDimensionDetail();
//            BeanUtils.copyProperties(score,detail);
//            // 维度信息放进去
//            interviewDimensions.stream().filter(interviewDimension -> interviewDimension.getId().equals(score.getDimensionId()))
//                    .findFirst()
//                    .ifPresent(interviewDimension -> {
//                        detail.setDimensionName(interviewDimension.getName());
//                        detail.setDescription(interviewDimension.getDescription());
//                        detail.setWeight(interviewDimension.getWeight());
//                        detail.setSort(interviewDimension.getSort());
//            });
//            return detail;
//        }).collect(Collectors.toList());
        List<ReportDimensionDetail> detailList = interviewDimensionScores.stream().map(score -> {
            ReportDimensionDetail detail = new ReportDimensionDetail();
            BeanUtils.copyProperties(score, detail);

            Long scoreDimId = score.getDimensionId();
            // 打印当前得分的dimensionId
            System.out.println("处理维度得分，score.getDimensionId() = " + scoreDimId);

            // 打印所有岗位维度id
            System.out.print("岗位维度id列表: ");
            for (InterviewDimension d : interviewDimensions) {
                System.out.print(d.getId() + " ");
            }
            System.out.println();

            // 查找维度
            InterviewDimension found = interviewDimensions.stream()
                    .filter(interviewDimension -> {
                        boolean match = interviewDimension.getId().equals(scoreDimId);
                        if (match) {
                            System.out.println("找到匹配维度: " + interviewDimension.getId() + " 名称: " + interviewDimension.getName());
                        }
                        return match;
                    })
                    .findFirst()
                    .orElse(null);

            if (found != null) {
                detail.setDimensionName(found.getName());
                detail.setDescription(found.getDescription());
                detail.setWeight(found.getWeight());
                detail.setSort(found.getSort());
            } else {
                System.out.println("未找到维度，score.getDimensionId() = " + scoreDimId);
            }
            return detail;
        }).collect(Collectors.toList());
        reportDetailEntity.setDimensionDetails(detailList);
        return reportDetailEntity;
    }

    private String genPromptString(List<InterviewDimension> interviewDimensions, List<InterviewQuestionAnswerEntity> questionAnswers){
        StringBuilder prompt = new StringBuilder();
        prompt.append("你是一位专业的IT技术面试评估专家，需要根据候选人的面试问题和回答内容，从不同维度进行评估并生成详细的面试报告。请按照以下要求进行分析：\n");
        // 评估维度
        prompt.append("### 评估维度\n");
        interviewDimensions.forEach(interviewDimension -> {
            prompt.append(String.format("%d.%s(权重%.0f%%)：评估Java专业知识、框架使用、系统设计等能力\n",
                    interviewDimension.getId(),
                    interviewDimension.getName(),
                    interviewDimension.getWeight().multiply(new BigDecimal("100")).setScale(2, BigDecimal.ROUND_HALF_UP)));
        });
        // 面试问题与回答
        prompt.append("### 面试问题与回答\n");
        for (int i = 0; i < questionAnswers.size(); i++) {
            InterviewQuestionAnswerEntity questionAnswer = questionAnswers.get(i);
            prompt.append(String.format("问题%d：%s\n",i+1,questionAnswer.getQuestionContent()));
            prompt.append(String.format("回答%d：%s\n",i+1,questionAnswer.getAnswerContent()));
        }
        prompt.append("""
            ### 评估要求
            1. 对每个维度进行评分(0-100分)，并给出具体评价
            2. 生成综合评分和总体评价
            3. 分析候选人的优势和不足
            4. 提供针对性的改进建议
            5. 保持评价专业、客观且有建设性
            6. 结果为JSON格式的字符串，不需要以markdown的方式生成，直接生成内容即可

            ### 输出格式
            请严格按照以下JSON格式输出评估结果：

            {
              "overall_score": 综合评分,
              "overall_evaluation": "总体评价",
              "dimension_scores": [
                {
                  "dimension_id": 维度ID,
                  "dimension_name": 维度名称,
                  "score": 维度得分,
                  "evaluation": "维度评价"
                },
                ...
              ],
              "strengths": "优势分析",
              "weaknesses": "不足分析",
              "suggestions": "改进建议"
            }
        """);
        return prompt.toString();
    }
}
